import datetime

from django.db.models import Q
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from sqlalchemy.exc import IntegrityError
from rest_framework import viewsets, status
from rest_framework.response import Response
from web.models import User, Group, GroupMember, Notice, Document, DocumentUser
from web.db.manage_db.manage_user import *


class DocumentSerializer(serializers.ModelSerializer):
    # write_only=True表示username字段仅用于从客户端接收数据（例如创建或更新文档），而不会在序列化输出中包含
    # username = serializers.CharField(write_only=True, required=False)

    # modify_right = serializers.IntegerField(write_only=True)
    # share_right = serializers.IntegerField(write_only=True)
    # discuss_right = serializers.IntegerField(write_only=True)
    # 字段被设置为write_only=True，这意味着它们在序列化输出中不会被包含。即使你在fields = "__all__"中包含了这些字段，它们在序列化时仍然不会被输出。
    class Meta:
        model = Document
        fields = "__all__"
    # def create(self, validated_data):
    #     print("Create method called")
    #     id = get_newid()
    #     user = User.objects.filter(username=validated_data.pop("username")).first()
    #     now = datetime.datetime.now()
    #     existing_document = Document.objects.filter(title=validated_data.get("title")).first()
    #     modify_right = validated_data.pop("modify_right")
    #     share_right = validated_data.pop("share_right")
    #     discuss_right = validated_data.pop("discuss_right")
    #     # 因为文档的名字是唯一的，所以如果存在同名文档，我们要修改同名文档里面除了文章标题的其他值
    #     if existing_document:
    #         for key, value in validated_data.items():
    #             setattr(existing_document, key, value)
    #         existing_document.creator_id = user.id
    #         existing_document.create_time = now
    #         existing_document.modified_time = None
    #         existing_document.modify_right = modify_right
    #         existing_document.share_right = share_right
    #         existing_document.discuss_right = discuss_right
    #         existing_document.other_modify_right = modify_right
    #         existing_document.other_share_right = share_right
    #         existing_document.others_discuss_right = discuss_right
    #         existing_document.recycled = 0
    #         existing_document.is_occupied = 0
    #         existing_document.group_id = 0
    #         new_document = existing_document
    #         new_document.save()
    #     else:
    #         new_document = Document.objects.create(
    #             id=id,
    #             create_time=now,
    #             creator_id=user.id,
    #             modify_right=modify_right,
    #             share_right=share_right,
    #             discuss_right=discuss_right,
    #             other_modify_right=modify_right,
    #             other_share_right=share_right,
    #             others_discuss_right=discuss_right,
    #             **validated_data
    #         )
    #     id = get_newid()
    #     new_du = DocumentUser(id=id,
    #                                  document_id=new_document.id,
    #                                  user_id=user.id,
    #                                  last_watch=None,
    #                                  favorited=0,
    #                                  modified_time=None,
    #                                  type=0
    #                                  )
    #     new_du.save()
    #     return new_document


# 当你在函数调用中使用**validated_data时，你实际上是将validated_data字典中的所有键值对作为关键字参数传递给函数。例如，如果validated_data是
# {'title': 'My Document', 'content': 'Hello, world!'}，那么Document.objects.create(**validated_data)等同于
# Document.objects.create(title='My Document', content='Hello, world!')

# 创建个人文档 (同时赋予权限)
class DocumentViewSet(viewsets.ModelViewSet):
    """/api/create_personal_doc/"""
    queryset = Document.objects.all()
    serializer_class = DocumentSerializer
    """
    这里的大概流程是这样，比如用户前台访问POST方法，传入document。由于继承了ModelViewSet，ModelViewSet继承了GenericViewSet、CreateModelMixin
    等等一些其他类，其中GenericViewSet继承的ViewSetMixin重写了as_view()方法，for循环修改了分发机制，就相当于访问post()会访问create(),
    这个create是CreateModelMixin里面的，在这里就相当于之前post里实现的逻辑，首先从前端获取数据，初始化数据，验证数据是否有效is_valid()，有效
    的数据调用save(),save方法会将前台获取的有效数据放在validated_data里面，然后调用create()方法并传入validated_data，这里的create()方法
    就是我们序列化器里面重写的，然后将validated_data里面的数据拿到并保存在数据库里面，最后serializer.save就相当于将数据保存到数据库，
    这个时候的instance就有值了，再通过视图函数里面的serializer.data反序列化给前端
    
    """

    # 查看我创建的文档(除团队文档外的文档)
    def list(self, request, *args, **kwargs):
        """
        /api/my_created_docs/# 获取我创建的所有文档的信息
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        print(request.query_params)
        username = request.query_params.get("username")
        user = User.objects.filter(username=username).first()
        print(user.id)
        all_document = Document.objects.filter(Q(creator_id=user.id) & Q(recycled=0))
        serializer = DocumentSerializer(instance=all_document, many=True)
        return Response(serializer.data)

# 创建个人文档 (同时赋予权限)
@api_view(['POST'])
def create_personal_doc(request):
    msg = ''
    if request.method == 'POST':
        id = get_newid()
        user = User.objects.filter(username=request.data.get('username')).first()
        creator_id = user.id
        now = datetime.datetime.now()
        formatted_now= now.strftime("%Y-%m-%d %H:%M:%S")
        content = request.data.get('content')
        msg = "success"
        existing_document = Document.objects.filter(title=request.data.get('title')).first()
        newDocument = None  # 声明 newDocument 变量
        if existing_document:
            # 如果已经存在具有相同title的文档，更新其余字段
            existing_document.creator_id = creator_id
            existing_document.create_time = formatted_now
            existing_document.modified_time = None
            existing_document.modify_right = request.data.get('modify_right')
            existing_document.share_right = request.data.get('share_right')
            existing_document.discuss_right = request.data.get('discuss_right')
            existing_document.others_modify_right = request.data.get('modify_right')
            existing_document.others_share_right = request.data.get('share_right')
            existing_document.others_discuss_right = request.data.get('discuss_right')
            existing_document.content = content
            existing_document.recycled = 0
            existing_document.is_occupied = 0
            existing_document.group_id = 0
            newDocument = existing_document
        else:
            document_data = {
                'id': id,
                'title': request.data.get('title'),
                'creator_id': creator_id,
                'create_time': formatted_now,
                'modified_time': None,
                'modify_right': request.data.get('modify_right'),
                'share_right': request.data.get('share_right'),
                'discuss_right': request.data.get('discuss_right'),
                'others_modify_right': request.data.get('modify_right'),
                'others_share_right': request.data.get('share_right'),
                'others_discuss_right': request.data.get('discuss_right'),
                'content': content,
                'recycled': 0,
                'is_occupied': 0,
                'group_id': 0
            }
            serializer = DocumentSerializer(data=document_data)
            print(document_data)
            if serializer.is_valid():
                newDocument = serializer.save()
            else:
                return Response(serializer.errors)
        try:
            newDU = DocumentUser(id=id, document_id=newDocument.id,
                                 user_id=user.id, last_watch=None,
                                 favorited=0, modified_time=None, type=0)
            newDU.save()
            return Response({"message": "success"})
        except IntegrityError:
            return Response({"message": "An error occurred while saving the document."})


# 创建团队文档 (同时赋予权限)
@api_view(['POST'])
def create_group_doc(request):
    """
    /api/create_group_doc/
    :param request:
    :return:
    """
    id = get_newid()
    user = User.objects.filter(username=request.data.get("username"))
    title = request.data.get("title")
    group_id = request.data.get("group_id")
    now = datetime.datetime.now()
    new_document_data = Document(id=id, title=title, creator_id=user.id,
                                 create_time=now, modified_time=None,
                                 modify_right=request.data.get('modify_right'),
                                 discuss_right=request.data.get('discuss_right'),
                                 others_modify_right=request.data.get('others_modify_right'),
                                 others_share_right=request.data.get('others_share_right'),
                                 others_discuss_right=request.data.get('others_discuss_right'),
                                 content=request.data.get("content"), recycled=0, is_occupied=0, group_id=group_id)
    serializer = DocumentSerializer(data=new_document_data)
    if serializer.is_valid():
        serializer.save()
        # 让团队的每个成员都可以看到该团队文档
        id = get_newid()
        i = 1
        all_member = GroupMember.objects.filter(group_id=group_id)
        for member in all_member:
            id = id + i
            DocumentUser.objects.create(id=id,
                                        document_id=serializer.data["id"],
                                        user_id=member.user_id,
                                        last_watch=None,
                                        favorited=0,
                                        modified_time=None,
                                        type=1
                                        )
            i += 1
        return Response({"message": "success"})
    else:
        return Response({"errors": "fail"})


@api_view(["POST"])
# 查看我拥有的文档(除团队文档外的文档)????????????????????????????不理解type!=1
def my_docs(request):
    username = request.data.get("username")
    user = User.objects.filter(username=username).first()
    all_du = DocumentUser.objects.filter(userid=user.id).first()
    res = []
    for du in all_du:
        document = Document.objects.filter(id=du.document_id).first()
        if all_du.type != 1 and document.recycled == 0:
            res.append(document)
    serializer = DocumentSerializer(instance=res, many=True)
    return Response(serializer.data)


# 查看我删除的文档,我删除的是我自己创建的
@api_view(["POST"])
def my_delete_docs(request):
    username = request.data.get("username")
    user = User.objects.filter(username=username).first()
    all_document = Document.objects.filter(creator_id=user.id, recycled=1)
    serializer = DocumentSerializer(instance=all_document, many=True)
    return Response(serializer.data)


# 传递权限信息?????????????????else type=1不懂
@api_view(["POST"])
def tell_doc_right(request):
    document = Document.objects.filter(id=request.data.get("DocumenID")).first()
    user = User.objects.filter(username=request.data.get("username")).first()
    DULink = DocumentUser.objects.filter(document_id=document.id, user_id=user.id).first()
    if DULink == None:
        response = {
            'watch_right': False,
            'modify_right': False,
            'share_right': False,
            'discuss_right': False,
            'others_modify_right': False,
            'others_share_right': False,
            'others_discuss_right': False,
            'others_watch_right': False,
            'doctype': -1,
            'usertype': -1,
            'isleader': False
        }
        return Response(response)
    elif document.creator_id == user.id:
        if document.group_id != 0:
            type = 0
            response = {
                'watch_right': True,
                'modify_right': True,
                'share_right': True,
                'discuss_right': True,
                'others_modify_right': True,
                'others_share_right': True,
                'others_discuss_right': True,
                'others_watch_right': True,
                'doctype': type,
                'usertype': DULink.type,
                'isleader': True
            }
            return Response(response)
    else:
        if document.group_id != 0:
            type = 0
        else:
            type = 1
        modify_right = toTF(document.modify_right)
        share_right = toTF(document.share_right)
        discuss_right = toTF(document.discuss_right)

        others_modify_right = toTF(document.others_modify_right)
        others_share_right = toTF(document.others_share_right)
        others_discuss_right = toTF(document.others_discuss_right)
        response = {
            'watch_right': True,
            'modify_right': modify_right,
            'share_right': share_right,
            'discuss_right': discuss_right,
            'others_modify_right': others_modify_right,
            'others_share_right': others_share_right,
            'others_discuss_right': others_discuss_right,
            'others_watch_right': True,
            'doctype': type,
            'usertype': DULink.type,
            'isleader': False
        }
        return Response(response)


# 告知文档当前权限
@api_view(['POST'])
def tell_current_doc_right(request):
    """
    /api/tell_current_doc_right/
    :param request:
    :return:
    """
    document = Document.objects.filter(id=request.data.get("DocumentID"))
    response = {
        'modify_right': document.modify_right,
        'share_right': document.share_right,
        'discuss_right': document.discuss_right,
        'others_modify_right': document.others_modify_right,
        'others_share_right': document.others_share_right,
        'others_discuss_right': document.others_discuss_right
    }
    return Response(response)


# 获取文档内容
@api_view(['POST'])
def get_doccontent(request):
    document = Document.objects.filter(id=request.data.get("DocumentID"))
    user = User.objects.filter(username=request.data.get("username"))

    if (document is None) or (user is None):
        return Response({"message": 'fail', "content": ''})
    if (document is not None) and (user is not None):
        DULink = DocumentUser.objects.filter(document_id=document.id, user_id=user.id)
        now = datetime.datetime.now()
        document = DocumentUser.objects.filter(document_id=document.id, user_id=user.id).update(last_watch=now)
        return Response({"message": 'success', "content": ''})
